<template>
  <div class="profile-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>个人设置</h2>
        <p>管理个人信息和账户设置</p>
      </div>
    </div>

    <!-- 设置内容 -->
    <div class="profile-content">
      <el-row :gutter="24">
        <!-- 基本信息 -->
        <el-col :span="16">
          <el-card>
            <template #header>
              <span>基本信息</span>
            </template>
            
            <el-form
              ref="profileFormRef"
              :model="profileForm"
              :rules="profileRules"
              label-width="100px"
            >
              <el-form-item label="头像">
                <div class="avatar-upload">
                  <el-avatar
                    :size="80"
                    :src="profileForm.avatar"
                    @error="handleAvatarError"
                  >
                    {{ profileForm.nickname?.charAt(0) || 'U' }}
                  </el-avatar>
                  <el-upload
                    class="avatar-uploader"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                    :http-request="uploadAvatar"
                  >
                    <el-button size="small">更换头像</el-button>
                  </el-upload>
                </div>
              </el-form-item>
              
              <el-form-item label="昵称" prop="nickname">
                <el-input
                  v-model="profileForm.nickname"
                  placeholder="请输入昵称"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
              
              <el-form-item>
                <el-button
                  type="primary"
                  @click="saveProfile"
                  :loading="savingProfile"
                >
                  保存信息
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <!-- 账户信息 -->
        <el-col :span="8">
          <el-card>
            <template #header>
              <span>账户信息</span>
            </template>
            
            <div class="account-info">
              <div class="info-item">
                <span class="label">用户ID：</span>
                <span class="value">{{ userInfo.id }}</span>
              </div>
              <div class="info-item">
                <span class="label">用户名：</span>
                <span class="value">{{ userInfo.name }}</span>
              </div>
              <div class="info-item">
                <span class="label">昵称：</span>
                <span class="value">{{ userInfo.nickname }}</span>
              </div>
              <div class="info-item">
                <span class="label">邮箱：</span>
                <span class="value">{{ userInfo.email }}</span>
              </div>
              <div class="info-item">
                <span class="label">个人简介：</span>
                <span class="value">{{ userInfo.bio || '暂无' }}</span>
              </div>
              <div class="info-item">
                <span class="label">注册时间：</span>
                <span class="value">{{ formatDate(userInfo.created_at) }}</span>
              </div>
              <div class="info-item">
                <span class="label">最后登录：</span>
                <span class="value">{{ formatDate(userInfo.last_login_at) }}</span>
              </div>
              <div class="info-item">
                <span class="label">登录次数：</span>
                <span class="value">{{ userInfo.login_count || 0 }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'
import { authApi, uploadApi } from '@/api/admin'

const authStore = useAuthStore()

// 用户信息
const userInfo = ref({})

// 表单引用
const profileFormRef = ref(null)

// 保存状态
const savingProfile = ref(false)

// 基本信息表单
const profileForm = ref({
  nickname: '',
  avatar: ''
})

// 基本信息验证规则
const profileRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 50, message: '昵称长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour12: false })
}

// 刷新用户信息并同步到 Pinia、userInfo、profileForm
const refreshUserInfo = async () => {
  try {
    const res = await authApi.getUserInfo()
    const user = res.data
    authStore.updateUserInfo(user)
    userInfo.value = user
    profileForm.value.avatar = user.avatar
    profileForm.value.nickname = user.nickname
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 使用本地存储的用户信息作为备选
    const localUser = authStore.user
    if (localUser) {
      userInfo.value = localUser
      profileForm.value.avatar = localUser.avatar || ''
      profileForm.value.nickname = localUser.nickname || ''
    }
  }
}

// 头像上传前检查
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传头像
const uploadAvatar = async (options) => {
  try {
    const response = await uploadApi.uploadAvatar(options.file)
    console.log(response)
    const avatarUrl = response.data.avatar
    profileForm.value.avatar = avatarUrl
    // 上传成功后，重新拉取用户信息并同步到 Pinia
    await refreshUserInfo()
    ElMessage.success('头像上传成功')
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  }
}

// 头像加载错误处理
const handleAvatarError = () => {
  // 头像加载失败时的处理
}

// 保存个人信息
const saveProfile = async () => {
  try {
    await profileFormRef.value.validate()
    savingProfile.value = true
    // 更新昵称
    await authApi.updateNickname({ nickname: profileForm.value.nickname })
    // 昵称修改后也刷新
    await refreshUserInfo()
    ElMessage.success('个人信息保存成功')
  } catch (error) {
    if (error !== false) {
      console.error('保存个人信息失败:', error)
      ElMessage.error('保存个人信息失败')
    }
  } finally {
    savingProfile.value = false
  }
}

// 组件挂载
onMounted(() => {
  refreshUserInfo()
})
</script>

<style scoped lang="scss">
.profile-page {
  background: #fafbfc;
  min-height: 100vh;
  padding: 32px 0;

  .page-header {
    margin-bottom: 24px;

    h2 {
      margin: 0 0 8px 0;
      font-size: 24px;
      color: #222;
    }

    p {
      margin: 0;
      color: #888;
      font-size: 14px;
    }
  }

  .profile-content {
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
    padding: 32px 24px;

    .avatar-upload {
      display: flex;
      align-items: center;
      gap: 16px;

      .avatar-uploader {
        .el-button {
          margin-top: 8px;
        }
      }
    }

    .account-info {
      .info-item {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .label {
          color: #666;
          font-size: 14px;
          min-width: 80px;
        }

        .value {
          color: #222;
          font-weight: 500;
          text-align: right;
          flex: 1;
          word-break: break-all;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .profile-page {
    padding: 16px 0;
    
    .profile-content {
      border-radius: 12px;
      padding: 16px 8px;
    }
  }
}
</style> 